import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  Animated,
  ScrollView,
  Image,
  TextInput,
  TouchableOpacity,
  Platform,
  Dimensions,
} from 'react-native';

import styles from '../order/editOrderStyle';
import CustomListView from '../global/CustomListView';
import ListViewActivityIndicator from '../global/ListViewActivityIndicator';
import api from '../../services/api';
import _ from 'lodash';
import moment from 'moment';

const {width: deviceWidth, height: deviceHeight} = Dimensions.get('window');

class WithdrawList extends Component {
    constructor(props) {
		super(props);

		this.state = {
            noData: false
		};

        // this._page = 0;
        this.totalpage = 0;
        this.pagesize = 20;
        this.list = [];
        this.currentPage = 1;

		// this.props.navigator.setOnNavigatorEvent(this._onNavigatorEvent.bind(this));
	}

    componentDidMount() {
        this.onLoad();
    }

    onLoad(){
        if(this.state.noData){
            this.setState({ noData: false});
        }

        this._withdrawByList._pullToRefreshListView.beginRefresh(true);
    }

    componentWillUnmount () {

    }

    _onSearchResultListItemPress(rowData){
        // this.props.parent.setState({addressFirst: `${rowData.first_address}${rowData.second_address}`});
    }

    async _getWithdrawList(){
        let list;

        //need to clear ListRowRefsCache manually
        this._withdrawByList._pullToRefreshListView.clearListRowRefsCache();

        list = await api.post('/order/tradelist', {
                   page:1,
                   pagesize:this.pagesize
                });

       this.list = {};
       if (list.cd == 1) {
           this.refs.toast.show(list.msg);
           this._withdrawByList && this._withdrawByList._pullToRefreshListView.endRefresh(false);
           return;
       }
       if(Platform.OS == 'ios') {
           this._endWithdrawList(list.data);
       } else {
           setTimeout(() => {
               this._endWithdrawList(list.data);
           }, 300);
       }
    }

    _endWithdrawList(list){
        this.totalpage = list.total_page;
        list = list.res;

        // console.log("###", list);
        if(list==null || list.length==0){
            this.setState({noData: true});
            return;
        }

        for (var i = 0; i < list.length; i++) {
            let dateArr = list[i].trade_time.split("-");
            if(this.list[dateArr[0]+'年'+dateArr[1]+'月']){
                this.list[dateArr[0]+'年'+dateArr[1]+'月'].push(list[i]);
            }else{
                this.list[dateArr[0]+'年'+dateArr[1]+'月'] = [list[i]];
            }
        }

        let list_copy = {...this.list};
        // this._updateListView();cloneWithRowsAndSections
        this.currentPage=1;
        this._withdrawByList && this._withdrawByList.setState({
            dataSource: this._withdrawByList._dataSource.cloneWithRowsAndSections(list_copy)
        });

        this._activityIndicator && this._activityIndicator.setState({ visible: false,});
        this._withdrawByList && this._withdrawByList._pullToRefreshListView.endRefresh(false);
    }

    async _retrieveNextPage() {
        let page, list;
        if (this.currentPage !== this.totalpage) {
            page = this.currentPage + 1;
            this.currentPage=page;

            list = await api.post('/order/tradelist', {
                       page:page,
                       pagesize:this.pagesize
                    });

            if(list.data){
                const newData = list.data.res;
                for (var i = 0; i < newData.length; i++) {
                    let dateArr = newData[i].trade_time.split("-");
                    if(this.list[dateArr[0]+'年'+dateArr[1]+'月']){
                        this.list[dateArr[0]+'年'+dateArr[1]+'月'].push(newData[i]);
                    }else{
                        this.list[dateArr[0]+'年'+dateArr[1]+'月'] = [newData[i]];
                    }
                }

                // newData.map((item, index) => this.list.push(item));

                this._withdrawByList.setState({
                    dataSource: this._withdrawByList._dataSource.cloneWithRowsAndSections(this.list),
                });

                this._withdrawByList._pullToRefreshListView.endLoadMore(false);
            }

        }else{
            this._withdrawByList._pullToRefreshListView.endLoadMore(true);
        }

	}

    _onRefresh(){
        this._getWithdrawList();
    }

    _onLoadMore(){
        this._retrieveNextPage();
    }

    _renderRow(rowData, sectionID, rowID){
        return (
            <View style={[styles.searchItem_,{marginLeft:0,flexDirection: 'row',alignItems:'center',justifyContent:'space-between'}]}>
                <View style={{paddingLeft: 15,width:'60%',marginTop:15,marginBottom:15}}>
                    <Text style={{fontSize: 13, color: '#555555',}}>{rowData.trade_name}</Text>
                    <Text style={{fontSize: 12, color: '#7B7B7B', marginTop: 5, }}>{rowData.trade_time}</Text>
                </View>
                <View style={{marginRight: 15,marginTop:15,marginBottom:15}}>
                    <Text style={{fontSize: 13, color: '#EA5404',textAlign:'right'}}>{rowData.trade_amount.toFixed(2)}</Text>
                    <Text style={{fontSize: 12, color: '#7B7B7B', marginTop: 5, textAlign:'right'}}>{rowData.status==2?(rowData.trade_name=='提现'?`手续费：${rowData.trade_fee}元，处理成功`:'处理成功'):(rowData.status==1?(rowData.trade_name=='提现'?`手续费：${rowData.trade_fee}元，处理中`:'处理中'):<Text style={{color:'red'}}>{rowData.trade_name=='提现'?`手续费：${rowData.trade_fee}元，处理失败`:'处理失败'}</Text>)}</Text>
                </View>
            </View>
        );
    }

    _renderSectionHeader(sectionData, sectionID){
        return (
            <View style={{paddingLeft:15,paddingTop:5,paddingBottom:5,backgroundColor:'#fff',borderBottomWidth:StyleSheet.hairlineWidth,borderColor:'#DEDEDE'}}>
                <Text style={{color: '#565656'}}>{sectionID}</Text>
            </View>
        )
    }

    _renderFloatSectionHeader(sectionID){
        return (
            <View style={{paddingLeft:15,paddingTop:5,paddingBottom:5,backgroundColor:'#fff',borderBottomWidth:StyleSheet.hairlineWidth,borderColor:'#DEDEDE'}}>
                <Text style={{color: '#565656'}}>{sectionID}</Text>
            </View>
        )
    }

    _renderNodata(){
        return (
            <View style={{alignItems:'center',justifyContent:'center',flex:1,backgroundColor:'#fff'}}>
                <Image source={require('../../../img/hk_nodata_icon.png')} style={styles.leftImage}/>
                <Text style={{fontSize: 13, color: '#B5B5B5',marginTop:10}}>暂无明细记录哦~</Text>
            </View>
        );
    }

    render() {
        return (
            this.state.noData?this._renderNodata():
            <View style={styles.withdrawContainer}>
                <CustomListView
                    style={{flex:1}}
                    ref={ (component) => this._withdrawByList = component }
                    onRefresh={this._onRefresh.bind(this)}
                    onLoadMore={this._onLoadMore.bind(this)}
                    renderRow ={this._renderRow.bind(this)}
                    renderFloatSectionHeader={this._renderFloatSectionHeader.bind(this)}
                    renderSectionHeader={this._renderSectionHeader.bind(this)}
                />
                <ListViewActivityIndicator
                    ref={ (component) => this._activityIndicator = component }
                    style={{marginRight: 10, position:'absolute', left: (deviceWidth - 20) / 2, top: (deviceHeight - 64 - 70) / 2, }}
                    color={'#a9a9a9'}/>
            </View>
        );
    }
}

var connectHelper = require('../../services/connectHelper');
WithdrawList = connectHelper(state => state)(WithdrawList);

module.exports = WithdrawList;
